package com.snatch.snatchnd.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.snatch.common.utils.SpringUtil;
import com.snatch.common.vo.NodeTaskInput;
import com.snatch.snatchnd.core.SnatchThread;
import com.snatch.snatchnd.service.AccountService;
import com.snatch.snatchnd.service.TaskService;

@Service
public class TaskServiceImpl implements TaskService {

	protected Logger logger = Logger.getLogger(TaskServiceImpl.class);

	/*private ExecutorService snatchExecutorService = Executors
			.newCachedThreadPool();// 抓取线程
*/
	private ConcurrentMap<String, ConcurrentHashMap<String,SnatchThread>> nodeTaskInputMap = new ConcurrentHashMap<String, ConcurrentHashMap<String,SnatchThread>>();// 每个抓取线程版本号内存队列

	@Autowired
	private AccountService accountManageService;

	@Autowired
	private NodeIntegration nodeIntegration;
	
	@Override
	public List<String> runSnatchTask(String webCode) {
		List<String> list = new ArrayList<String>();
		if(null != nodeTaskInputMap.get(webCode)){
			list.addAll(nodeTaskInputMap.get(webCode).keySet());
		}
		return list;
	}


	@Override
	public int snatchTask(NodeTaskInput nodeTaskInput) {
		ConcurrentHashMap<String,SnatchThread> webSnatchs = nodeTaskInputMap.get(nodeTaskInput.getWebCode());
		if(null == webSnatchs){
			webSnatchs = new ConcurrentHashMap<String,SnatchThread>();
			nodeTaskInputMap.put(nodeTaskInput.getWebCode(), webSnatchs);
		}
		
		if (webSnatchs.get(nodeTaskInput.getTaskCode()) != null) {
			return -1;
		}
		
		SnatchThread snatchThread = (SnatchThread)SpringUtil.getBean("snatchThread");
		snatchThread.init(nodeTaskInput);
		snatchThread.start();
		webSnatchs.put(nodeTaskInput.getTaskCode(), snatchThread);
		return 1;
	}

	
}
